//
//  OpenSDK_PayManager.m
//  OpenSDK
//
//  Created by wyht－ios－dev on 16/3/7.
//  Copyright © 2016年 WYHT. All rights reserved.
//

#import "OpenSDK_PayManager.h"
#import "OpenSDK.h"
#import "OpenSDK_DataManager.h"
#import "OpenSDK_StatisticsManager.h"
#import "OpenSDK_StatusManager.h"

#import "OpenSDK_PayProtocol.h"
#import "OpenSDK_Toast.h"
#import "OpenSDK_EventKeys.h"
#import "OpenSDK_Enum.h"
#import "OpenSDK_HttpUtil.h"

@implementation OpenSDK_PayManager

static OpenSDK_PayManager *instance = nil;

+(instancetype) getInstance
{
    if(instance==nil)
    {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            instance = [[self alloc] init];
        });
    }
    return instance;
}

// 回调游戏支付取消
-(void) callbackPayCancel {
    if ([OpenSDK getInstance].delegate) {
        [[OpenSDK getInstance].delegate openSDKPayWithCode:OpenSDK_PAY_CANCEL orderInfo:nil errStr:nil];
    }
    // 结束支付操作
    [[OpenSDK_StatusManager getInstance] setPayStatus:NO];
}

// 回调游戏支付成功
-(void) callbackPaySuccess:(NSString *) msg
                 withOrder:(OpenSDK_OrderInfo *) order {
    if ([OpenSDK getInstance].delegate) {
        [[OpenSDK getInstance].delegate openSDKPayWithCode:OpenSDK_PAY_SUCCESS orderInfo:order errStr:msg];
    }
    // 结束支付操作
    [[OpenSDK_StatusManager getInstance] setPayStatus:NO];
}

// 回调游戏支付失败
-(void) callbackPayFail:(NSString *) msg
              withOrder:(OpenSDK_OrderInfo *) order {
    if ([OpenSDK getInstance].delegate) {
        [[OpenSDK getInstance].delegate openSDKPayWithCode:OpenSDK_PAY_FAIL orderInfo:order errStr:msg];
    }
    BOOL iToast = [OpenSDK_DataManager getInstance].isPayToastEnable;
    if (!iToast){
        dispatch_async(dispatch_get_main_queue(), ^{
            [[OpenSDK_iToast makeText:@"支付失败，请重试。"] show];
        });
    }
    // 结束支付操作
    [[OpenSDK_StatusManager getInstance] setPayStatus:NO];
}

// 回调游戏支付状态待定
-(void) callbackPayWaitCheck:(OpenSDK_OrderInfo *) order {
    if ([OpenSDK getInstance].delegate) {
        [[OpenSDK getInstance].delegate openSDKPayWithCode:OpenSDK_PAY_WAIT_CHECK orderInfo:order errStr:nil];
    }
    // 结束支付操作
    [[OpenSDK_StatusManager getInstance] setPayStatus:NO];
}

-(void) pay:(OpenSDK_PayInfo *) payInfo serverName:(NSString *)serverName {
    id<OpenSDK_PayProtocol> sdk = [[OpenSDK_DataManager getInstance].supportSDKServerNames objectForKey:serverName];
    BOOL needStatistics = [sdk respondsToSelector:NSSelectorFromString(@"getStatisticsType")];
    if (needStatistics) {
        // 统计选择支付方式
        [[OpenSDK_StatisticsManager getInstance] collectPayActionWithType:OPENSDK_STATS_PAY_SUB
                                                                cpOrderId:payInfo.appData
                                                                   detail:[sdk getStatisticsType]];
    }
    
    [payInfo setPlatform:[sdk getPlatform]];
    [payInfo setPayVersion:[sdk getPlatformVersion]];
    // sdk创建opensdk订单，是否需要额外的参数
    if ([sdk respondsToSelector:NSSelectorFromString(@"beforeCreateOrder:")]) {
        [sdk beforeCreateOrder:payInfo];
    }
    [OpenSDK_HttpUtil createOrderWithPayInfo:payInfo httpDelegate:^(OpenSDK_BaseResData *resData) {
        if([resData isOk]) {
            OpenSDK_PayResData *payData=[[OpenSDK_PayResData alloc] initWithData:resData.content];
            // 统计创建订单成功
            if (needStatistics) {
                [[OpenSDK_StatisticsManager getInstance] collectPaySuccessWithType:OPENSDK_STATS_CREATE_ORDER_SUCCESS orderId:[payData getOrderID] cpOrderId:payInfo.appData detail:[sdk getStatisticsType]];
            }
            
            // 调起sdk的支付接口
            dispatch_async(dispatch_get_main_queue(), ^{
                [sdk startPay:payData];
            });
        } else {
            // 统计创建订单失败
            if (needStatistics) {
                [[OpenSDK_StatisticsManager getInstance] collectPayFailWithType:OPENSDK_STATS_CREATE_ORDER_FAIL orderId:nil cpOrderId:payInfo.appData detail:[sdk getStatisticsType] failInfo:resData.errorMsg];
            }
            // 回调游戏支付失败
            [self callbackPayFail:[resData errorMsg] withOrder:nil];
        }
    }];
}

@end

